import React from 'react';
import PropTypes from 'prop-types';

const connect = (mapStateToProps = (state) => {}, mapDispatchToProps = {}) => (Comp) => {
    return class extends React.Component{
        static contextTypes = {
            store: PropTypes.object
        }
        constructor(props, context){
            super(props, context);

            this.state = {
                props: {

                }
            }
        }

        componentDidMount(){
            this.up();

            const { store } = this.context;
            store.subscribe(() => {
                this.up();
            })
        }

        up(){
            
            const { store } = this.context;
            const state = mapStateToProps(store.getState());
            const dispatch = store.dispatch;
            const dispatchs = mapDispatchToProps;
            const dispatchList = {

            };

            for(let k in dispatchs){
                dispatchList[k] = (...args) => {
                    dispatch(dispatchs[k](...args));
                }
            }

            this.setState({
                props: {
                    ...this.state.props,
                    ...state,
                    ...dispatchList,
                }
            });
        }

        render(){
            return <Comp {...this.state.props} />
        }
    }
};


/**
 * 1. 接受store
 * 2. 定义全局的store
 * 3. 原样返回子组件
 * 主要的作用就是把create store 的 store扔到全局上共享
 */
class Provider extends React.Component{
    static childContextTypes = {
        store: PropTypes.object
    }

    getChildContext(){
        return {
            store: this.store
        }
    }

    constructor(props, context){
        super(props, context);
        this.store = props.store;
    }
    
    render(){
        return this.props.children;
    }
}

export { connect, Provider };